import { Context } from "egg";

module.exports = () => {
  return async (ctx: Context, next) => {
    const { socket } = ctx;
    const {
      id,
      handshake: { query },
    } = socket;

    ctx.logger.debug("id", id, "query", query);

    const { token } = query;
    if (!token) {
      ctx.logger.error("不存在token");
      socket.disconnect();
      await next();
      return;
    }

    try {
      // 解密TOKEN
      const decode = ctx.service.encryption.decodeToken(("Bearer " + token) as string);

      const { storeId, source } = decode.sub;

      socket.join(`storeId:${storeId}`);

      await next();

      ctx.logger.debug("disconnection");
    } catch (e) {
      ctx.logger.error("socket解析失败", e, token);
      socket.disconnect();
      await next();
    }
  };
};
